package com.smart.translator.ui.keyinfo;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.smart.translator.R;
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class KeyInfoActivity extends AppCompatActivity {
    private RecyclerView recyclerView;
    private KeyInfoAdapter adapter;
    private List<KeyInfo> keyInfoList = new ArrayList<>();
    private static final String PREFS_NAME = "key_settings";
    private static final String KEY_POSITIONS = "key_positions";
    
    // 分组定义
    public static final String[] GROUP_NAMES = {"微信", "QQ", "Facebook", "WhatsApp", "其他"};
    public static final int MAX_GROUP_COUNT = 4; // 每个分组最多4个ID

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_key_info);
        
        // 设置标题
        setTitle("键位信息管理");
        
        recyclerView = findViewById(R.id.recycler_view);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        
        adapter = new KeyInfoAdapter(keyInfoList, this::showEditDialog);
        recyclerView.setAdapter(adapter);
        
        loadKeyInfo();
    }
    
    private void loadKeyInfo() {
        try {
            SharedPreferences prefs = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
            String json = prefs.getString(KEY_POSITIONS, "[]");
            JSONArray array = new JSONArray(json);
            
            keyInfoList.clear();
            for (int i = 0; i < array.length(); i++) {
                JSONObject obj = array.getJSONObject(i);
                KeyInfo keyInfo = new KeyInfo();
                keyInfo.setNumber(obj.getInt("number"));
                keyInfo.setX((int) obj.getDouble("x"));
                keyInfo.setY((int) obj.getDouble("y"));
                keyInfo.setRadius((float) obj.getDouble("radius"));
                keyInfo.setDescription(obj.optString("description", "未设置"));
                keyInfo.setGroupIndex(obj.optInt("groupIndex", 0));
                keyInfo.setGroupId(obj.optInt("groupId", -1));
                keyInfoList.add(keyInfo);
                
                // 添加调试信息
                android.util.Log.d("KeyInfoActivity", "加载键位 " + keyInfo.getNumber() + 
                    ": 分组=" + keyInfo.getGroupIndex() + 
                    ", ID=" + keyInfo.getGroupId() + 
                    ", 描述=" + keyInfo.getDescription());
            }
            
            adapter.notifyDataSetChanged();
            android.util.Log.d("KeyInfoActivity", "加载完成，共加载 " + keyInfoList.size() + " 个键位");
            
            if (keyInfoList.isEmpty()) {
                findViewById(R.id.tv_empty).setVisibility(View.VISIBLE);
                recyclerView.setVisibility(View.GONE);
            } else {
                findViewById(R.id.tv_empty).setVisibility(View.GONE);
                recyclerView.setVisibility(View.VISIBLE);
            }
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(this, "加载键位信息失败", Toast.LENGTH_SHORT).show();
        }
    }
    
    private void showEditDialog(KeyInfo keyInfo) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("编辑键位 " + keyInfo.getNumber() + " 的配置");
        
        View dialogView = LayoutInflater.from(this).inflate(R.layout.dialog_key_info_edit, null);
        EditText editText = dialogView.findViewById(R.id.et_description);
        Spinner spinnerGroup = dialogView.findViewById(R.id.spinner_group);
        Spinner spinnerId = dialogView.findViewById(R.id.spinner_id);
        
        editText.setText(keyInfo.getDescription());
        
        // 设置分组选择器
        android.widget.ArrayAdapter<String> groupAdapter = new android.widget.ArrayAdapter<>(
            this, android.R.layout.simple_spinner_item, GROUP_NAMES);
        groupAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinnerGroup.setAdapter(groupAdapter);
        spinnerGroup.setSelection(keyInfo.getGroupIndex());
        
        // 设置ID选择器
        String[] idOptions = {"未调起输入法点击输入框", "未调起输入法点击发送按钮", 
                             "调起输入法点击输入框", "调起输入法点击发送按钮"};
        android.widget.ArrayAdapter<String> idAdapter = new android.widget.ArrayAdapter<>(
            this, android.R.layout.simple_spinner_item, idOptions);
        idAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinnerId.setAdapter(idAdapter);
        
        if (keyInfo.getGroupId() >= 0 && keyInfo.getGroupId() < 4) {
            spinnerId.setSelection(keyInfo.getGroupId());
        }
        
        builder.setView(dialogView);
        
        builder.setPositiveButton("保存", (dialog, which) -> {
            String description = editText.getText().toString().trim();
            if (description.isEmpty()) {
                description = "未设置";
            }
            
            int groupIndex = spinnerGroup.getSelectedItemPosition();
            int groupId = spinnerId.getSelectedItemPosition();
            
            // 添加调试信息
            android.util.Log.d("KeyInfoActivity", "用户选择: 分组=" + groupIndex + 
                "(" + GROUP_NAMES[groupIndex] + "), ID=" + groupId + 
                ", 描述=" + description);
            
            // 检查ID是否重复
            if (groupId >= 0) {
                for (KeyInfo existingKey : keyInfoList) {
                    if (existingKey != keyInfo && 
                        existingKey.getGroupIndex() == groupIndex && 
                        existingKey.getGroupId() == groupId) {
                        Toast.makeText(this, "该分组下的ID已被使用", Toast.LENGTH_SHORT).show();
                        return;
                    }
                }
            }
            
            keyInfo.setDescription(description);
            keyInfo.setGroupIndex(groupIndex);
            keyInfo.setGroupId(groupId);
            saveKeyInfo();
            adapter.notifyDataSetChanged();
            Toast.makeText(this, "保存成功", Toast.LENGTH_SHORT).show();
        });
        
        builder.setNegativeButton("取消", null);
        builder.show();
    }
    
    private void saveKeyInfo() {
        try {
            SharedPreferences prefs = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
            JSONArray array = new JSONArray();
            for (KeyInfo keyInfo : keyInfoList) {
                JSONObject obj = new JSONObject();
                obj.put("number", keyInfo.getNumber());
                obj.put("x", keyInfo.getX());
                obj.put("y", keyInfo.getY());
                obj.put("radius", keyInfo.getRadius());
                obj.put("description", keyInfo.getDescription());
                obj.put("groupIndex", keyInfo.getGroupIndex());
                obj.put("groupId", keyInfo.getGroupId());
                array.put(obj);
                
                // 添加调试信息
                android.util.Log.d("KeyInfoActivity", "保存键位 " + keyInfo.getNumber() + 
                    ": 分组=" + keyInfo.getGroupIndex() + 
                    ", ID=" + keyInfo.getGroupId() + 
                    ", 描述=" + keyInfo.getDescription());
            }
            prefs.edit().putString(KEY_POSITIONS, array.toString()).apply();
            android.util.Log.d("KeyInfoActivity", "保存成功，共保存 " + keyInfoList.size() + " 个键位");
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(this, "保存失败", Toast.LENGTH_SHORT).show();
        }
    }
    
    public static class KeyInfo {
        private int number;
        private int x;
        private int y;
        private float radius;
        private String description;
        private int groupIndex;
        private int groupId;
        
        public int getNumber() { return number; }
        public void setNumber(int number) { this.number = number; }
        
        public int getX() { return x; }
        public void setX(int x) { this.x = x; }
        
        public int getY() { return y; }
        public void setY(int y) { this.y = y; }
        
        public float getRadius() { return radius; }
        public void setRadius(float radius) { this.radius = radius; }
        
        public String getDescription() { return description; }
        public void setDescription(String description) { this.description = description; }
        
        public int getGroupIndex() { return groupIndex; }
        public void setGroupIndex(int groupIndex) { this.groupIndex = groupIndex; }
        
        public int getGroupId() { return groupId; }
        public void setGroupId(int groupId) { this.groupId = groupId; }
    }
    
    private static class KeyInfoAdapter extends RecyclerView.Adapter<KeyInfoAdapter.ViewHolder> {
        private List<KeyInfo> keyInfoList;
        private OnItemClickListener listener;
        
        public interface OnItemClickListener {
            void onItemClick(KeyInfo keyInfo);
        }
        
        public KeyInfoAdapter(List<KeyInfo> keyInfoList, OnItemClickListener listener) {
            this.keyInfoList = keyInfoList;
            this.listener = listener;
        }
        
        @Override
        public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.item_key_info, parent, false);
            return new ViewHolder(view);
        }
        
        @Override
        public void onBindViewHolder(ViewHolder holder, int position) {
            KeyInfo keyInfo = keyInfoList.get(position);
            holder.tvNumber.setText("键位 " + keyInfo.getNumber());
            holder.tvPosition.setText("位置: (" + keyInfo.getX() + ", " + keyInfo.getY() + ")");
            holder.tvRadius.setText("大小: " + (int) keyInfo.getRadius() + "px");
            holder.tvDescription.setText("含义: " + keyInfo.getDescription());
            
            // 显示分组和ID信息
            String groupName = GROUP_NAMES[keyInfo.getGroupIndex()];
            String groupInfo;
            if (keyInfo.getGroupId() >= 0) {
                String[] idNames = {"未调起输入法点击输入框", "未调起输入法点击发送按钮", 
                                   "调起输入法点击输入框", "调起输入法点击发送按钮"};
                groupInfo = groupName + " - " + idNames[keyInfo.getGroupId()];
            } else {
                groupInfo = groupName + " - 未配置ID";
            }
            holder.tvGroup.setText("分组: " + groupInfo);
            
            holder.btnEdit.setOnClickListener(v -> {
                if (listener != null) {
                    listener.onItemClick(keyInfo);
                }
            });
        }
        
        @Override
        public int getItemCount() {
            return keyInfoList.size();
        }
        
        static class ViewHolder extends RecyclerView.ViewHolder {
            TextView tvNumber, tvPosition, tvRadius, tvDescription, tvGroup;
            Button btnEdit;
            
            ViewHolder(View itemView) {
                super(itemView);
                tvNumber = itemView.findViewById(R.id.tv_number);
                tvPosition = itemView.findViewById(R.id.tv_position);
                tvRadius = itemView.findViewById(R.id.tv_radius);
                tvDescription = itemView.findViewById(R.id.tv_description);
                tvGroup = itemView.findViewById(R.id.tv_group);
                btnEdit = itemView.findViewById(R.id.btn_edit);
            }
        }
    }
    
    // 外部接口：根据ID获取按钮位置
    public static class KeyPositionManager {
        private static final String PREFS_NAME = "key_settings";
        private static final String KEY_POSITIONS = "key_positions";
        
        public static Point getButtonPosition(Context context, int groupIndex, int groupId) {
            try {
                SharedPreferences prefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
                String json = prefs.getString(KEY_POSITIONS, "[]");
                JSONArray array = new JSONArray(json);
                
                for (int i = 0; i < array.length(); i++) {
                    JSONObject obj = array.getJSONObject(i);
                    int savedGroupIndex = obj.optInt("groupIndex", 0);
                    int savedGroupId = obj.optInt("groupId", -1);
                    
                    if (savedGroupIndex == groupIndex && savedGroupId == groupId) {
                        int x = (int) obj.getDouble("x");
                        int y = (int) obj.getDouble("y");
                        return new Point(x, y);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }
        
        public static class Point {
            public int x, y;
            public Point(int x, int y) {
                this.x = x;
                this.y = y;
            }
        }
    }
} 